package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignClient;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 处理社交登录
 */

@Controller
@Slf4j
public class Oauth2Controller {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private MemberFeignClient memberFeignClient;

    @GetMapping("/oauth2.0/weibo/success")
    public String getAuthCode(@RequestParam("code") String code, HttpSession session) {
        //1.根据code换取accessToken
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("client_id", "733003055");
        params.add("client_secret", "a34d611b085cabc6b75f87378f583671");
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        params.add("code", code);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

        ResponseEntity<SocialUser> responseEntity = restTemplate.postForEntity("https://api.weibo.com/oauth2/access_token", request, SocialUser.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.value() == 200) {
            SocialUser socialUser = responseEntity.getBody();
            R r = memberFeignClient.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("用户信息：{}" + data.toString());
                session.setAttribute(AuthConstant.LOGIN_USER, data);
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
        //2.登录成功就跳回首页
        return "redirect:http://gulimall.com";
    }

}
